<template>
  <div class="edit-course-category">
    <el-form
      :model="editForm"
      ref="editForm"
      label-width="70px"
      :rules="rules"
      style="width: 400px; margin: 10px 14px"
    >
      <el-form-item
        label="课程分类名称"
        label-width="106px"
        prop="courseCategoryName"
      >
        <el-input
          v-model="editForm.courseCategoryName"
          autocomplete="off"
          :clearable="true"
          @input="changeForm"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态" label-width="106px" prop="status">
        <el-select
          v-model="editForm.status"
          autocomplete="off"
          :clearable="true"
          :popper-append-to-body="false"
          style="width: 120px"
          @input="changeForm"
        >
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          v-show="isShow"
          type="success"
          @click="update"
          :loading="updateLoading"
          >更新</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  getCourseCategoryById,
  updateCourseCategory,
} from "@/api/admin/courseCategory";
export default {
  name: "EditCourseCategoryView",
  data() {
    return {
      editForm: {},
      copyForm: {},
      rules: {
        courseCategoryName: [
          { required: true, message: "请输入课程分类名称", trigger: "blur" },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }],
      },
      isShow: false,
      updateLoading: false,
    };
  },
  props: ["id"],
  created() {
    this.getCourseCategoryInfo();
  },
  methods: {
    // 检测表单数据是否修改
    changeForm() {
      const objectEqual =
        JSON.stringify(this.editForm) === JSON.stringify(this.copyForm);
      if (!objectEqual) {
        this.isShow = true;
      } else {
        this.isShow = false;
      }
    },
    // 获取课程分类信息
    async getCourseCategoryInfo() {
      const res = await getCourseCategoryById(this.id);
      this.editForm = Object.assign({}, res.data);
      this.copyForm = Object.assign({}, res.data);
      this.editForm.status = this.editForm.status.toString();
      this.copyForm.status = this.copyForm.status.toString();
    },
    // 更新数据
    update() {
      this.$refs.editForm.validate(async (v) => {
        if (v) {
          try {
            this.updateLoading = true;
            const res = await updateCourseCategory(this.editForm);
            this.$router.push({
              name: "AdminCourseCategory",
            });
          } finally {
            this.updateLoading = false;
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.edit-course-category {
  width: 100%;
  height: 100%;
}
// 解决下拉框显示不完整问题
/deep/.el-select-dropdown__wrap.el-scrollbar__wrap {
  margin-bottom: 0 !important;
}
</style>